@rendermode InteractiveServer
@using DaoHang.Services
@using DaoHang.Models
@inject ICategoryService CategoryService
@inject IJSRuntime JSRuntime

<div class="card">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">
            <i class="bi bi-grid-3x3-gap me-2"></i>分类管理
        </h5>
        <button class="btn btn-primary btn-sm" @onclick="ShowAddCategoryModal">
            <i class="bi bi-plus-lg me-1"></i>添加分类
        </button>
    </div>
    <div class="card-body">
        @if (isLoadingCategories)
        {
            <div class="text-center py-4">
                <div class="spinner-border text-primary" role="status"></div>
                <p class="mt-2">加载中...</p>
            </div>
        }
        else if (categories.Any())
        {
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>分类名称</th>
                            <th>描述</th>
                            <th>图标</th>
                            <th>网站数量</th>
                            <th>排序</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var category in categories)
                        {
                            <tr>
                                <td>@category.Name</td>
                                <td>@(string.IsNullOrEmpty(category.Description) ? "-" : category.Description)</td>
                                <td>
                                    @if (!string.IsNullOrEmpty(category.IconClass))
                                    {
                                        <i class="@category.IconClass"></i>
                                    }
                                    else
                                    {
                                        <span class="text-muted">-</span>
                                    }
                                </td>
                                <td>@category.WebsiteCount</td>
                                <td>@category.SortOrder</td>
                                <td>
                                    <div class="btn-group btn-group-sm">
                                        <button class="btn btn-outline-primary" 
                                                @onclick="() => EditCategory(category)">
                                            <i class="bi bi-pencil"></i>
                                        </button>
                                        <a class="btn btn-outline-success" 
                                           href="/ai-recommendation/@category.Id" 
                                           target="_blank">
                                            <i class="bi bi-robot"></i>
                                        </a>
                                        <button class="btn btn-outline-danger" 
                                                @onclick="() => DeleteCategory(category.Id)">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </div>
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        }
        else
        {
            <div class="text-center py-4 text-muted">
                <i class="bi bi-inbox display-4"></i>
                <p class="mt-2">暂无分类数据</p>
            </div>
        }
    </div>
</div>

<!-- 添加/编辑分类模态框 -->
@if (showModal)
{
    <div class="modal-backdrop fade show" @onclick="HideModal"></div>
    <div class="modal fade show" style="display: block; z-index: 1051;" tabindex="-1">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">
                        @(isEditingCategory ? "编辑分类" : "添加分类")
                    </h5>
                    <button type="button" class="btn-close" @onclick="HideModal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">分类名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" @bind="currentCategory.Name" required />
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">描述</label>
                        <textarea class="form-control" rows="3" @bind="currentCategory.Description"></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">图标类名</label>
                        <div class="input-group">
                            <span class="input-group-text">
                                <i class="@(string.IsNullOrEmpty(currentCategory.IconClass) ? "bi bi-grid" : currentCategory.IconClass)"></i>
                            </span>
                            <input type="text" class="form-control" @bind="currentCategory.IconClass" 
                                   placeholder="例如：bi bi-globe" />
                        </div>
                        <small class="text-muted">
                            使用Bootstrap Icons图标类名，可在 
                            <a href="https://icons.getbootstrap.com/" target="_blank">https://icons.getbootstrap.com/</a> 
                            查找
                        </small>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">排序权重</label>
                        <input type="number" class="form-control" @bind="currentCategory.SortOrder" min="0" />
                        <small class="text-muted">数字越小排序越靠前</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" @onclick="HideModal">取消</button>
                    <button type="button" class="btn btn-primary" @onclick="SaveCategory">保存</button>
                </div>
            </div>
        </div>
    </div>
}

@code {
    /// <summary>
    /// 分类数据列表
    /// </summary>
    private List<Category> categories = new List<Category>();

    /// <summary>
    /// 当前正在编辑的分类
    /// </summary>
    private Category currentCategory = new Category();

    /// <summary>
    /// 是否正在加载分类数据
    /// </summary>
    private bool isLoadingCategories = true;

    /// <summary>
    /// 是否正在编辑分类（区分添加和编辑模式）
    /// </summary>
    private bool isEditingCategory = false;

    /// <summary>
    /// 是否显示模态框
    /// </summary>
    private bool showModal = false;

    /// <summary>
    /// 组件初始化时加载数据
    /// </summary>
    protected override async Task OnInitializedAsync()
    {
        await LoadCategoriesAsync();
    }

    /// <summary>
    /// 加载分类数据
    /// </summary>
    private async Task LoadCategoriesAsync()
    {
        isLoadingCategories = true;
        try
        {
            categories = await CategoryService.GetAllCategoriesAsync();
        }
        catch (Exception)
        {
            // 处理异常
            categories = new List<Category>();
        }
        finally
        {
            isLoadingCategories = false;
            StateHasChanged();
        }
    }

    /// <summary>
    /// 显示添加分类的模态框
    /// </summary>
    private void ShowAddCategoryModal()
    {
        isEditingCategory = false;
        currentCategory = new Category
        {
            SortOrder = 0,
            IconClass = "bi bi-grid"
        };
        StateHasChanged();
        showModal = true;
    }

    /// <summary>
    /// 编辑分类信息
    /// </summary>
    private void EditCategory(Category category)
    {
        isEditingCategory = true;
        currentCategory = new Category
        {
            Id = category.Id,
            Name = category.Name,
            Description = category.Description,
            IconClass = category.IconClass,
            SortOrder = category.SortOrder
        };
        StateHasChanged();
        showModal = true;
    }

    /// <summary>
    /// 删除分类
    /// </summary>
    private async Task DeleteCategory(int id)
    {
        bool confirmed = await JSRuntime.InvokeAsync<bool>("confirm", "删除分类将同时删除该分类下的所有网站，确定要删除吗？");
        if (confirmed)
        {
            try
            {
                await CategoryService.DeleteCategoryAsync(id);
                await LoadCategoriesAsync();
            }
            catch (Exception)
            {
                await JSRuntime.InvokeVoidAsync("alert", "删除分类失败，可能是因为该分类下还有网站");
            }
        }
    }

    /// <summary>
    /// 保存分类信息
    /// </summary>
    private async Task SaveCategory()
    {
        // 表单验证
        if (string.IsNullOrWhiteSpace(currentCategory.Name))
        {
            await JSRuntime.InvokeVoidAsync("alert", "请输入分类名称");
            return;
        }

        try
        {
            if (isEditingCategory)
            {
                await CategoryService.UpdateCategoryAsync(currentCategory);
            }
            else
            {
                await CategoryService.AddCategoryAsync(currentCategory);
            }

            // 关闭模态框
            showModal = false;
            
            // 重新加载数据
            await LoadCategoriesAsync();
        }
        catch (Exception)
        {
            await JSRuntime.InvokeVoidAsync("alert", "保存分类信息失败，请重试");
        }
    }

    /// <summary>
    /// 隐藏模态框
    /// </summary>
    private void HideModal()
    {
        showModal = false;
    }
} 